using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MyUnityLib.Tool;
using MyUnityLib.ClassExtension;
using MyUnityLib.UI;
using UnityEngine.UI;
using MonsterLove.StateMachine;

namespace ProductExpirationAssistant
{
    /// <summary>上为横幅，正面是TableView结构的面板</summary>
    public class BarTableViewPanel : MonoBehaviour, TableViewData
    {
        /// <summary>下架生产日期Item</summary>
        public GameObject offShelfProductionDateItemPrefab;
        /// <summary>下架日期Item</summary>
        public GameObject offShelfDateItemPrefab;

        private TableView m_TableView;
        private Toggle m_LockUIRespondToggle;

        private StateMachine<FunctionType, Driver> m_FSM;

        private void Awake()
        {
            m_TableView = transform.FindComponentByPath<TableView>("TableView");

            UITool.BindButtonEvent(transform.Find("Bar"), ClickButton);

            m_LockUIRespondToggle = transform.FindComponentByPath<Toggle>("Bar/LockUIRespondToggle");
            m_LockUIRespondToggle.onValueChanged.AddListener(OnLockUIRespondChanged);

            Messenger.AddListener(EventName.TodayDateChanged, Reload);
            Messenger.AddListener(EventName.FunctionChanged, OnFunctionTypeChanged);
        }
        private void OnDestroy()
        {
            PoolsManager.ins.ClearPool(offShelfProductionDateItemPrefab.name);

            try
            {
                Messenger.RemoveListener<TipPopupPanel.ReplyKind>(EventName.CloseTipPopup, OnCloseTipPopup);
            }
            catch (System.Exception) { }
            Messenger.RemoveListener(EventName.TodayDateChanged, Reload);
            Messenger.RemoveListener(EventName.FunctionChanged, OnFunctionTypeChanged);

            m_FSM.Driver.Destroy.Invoke();
        }

        private void Start()
        {
            m_TableView.visibleSize = this.RectTransform().rect.size;
            m_TableView.Init(this);

            m_FSM = new StateMachine<FunctionType, Driver>(this);
            m_FSM.ChangeState(DataManager.ins.functionType);
        }

        private void ClickButton(Button button)
        {
            switch (button.name)
            {
                case "NewBtn":
                    {
                        m_FSM.Driver.NewBtn.Invoke();
                        break;
                    }
                case "ClearBtn":
                    {
                        Messenger.AddListener<TipPopupPanel.ReplyKind>(EventName.CloseTipPopup, OnCloseTipPopup);
                        Messenger.Broadcast<TipPopupPanel.Kind, string>(EventName.ShowTipPopup, TipPopupPanel.Kind.Yes_No, "确定删除所有记录");
                        break;
                    }
            }
        }

        private void OnLockUIRespondChanged(bool l)
        {
            foreach (var btn in transform.Find("Bar").FindComponentsInChildren<Button>(false))
            {
                btn.interactable = !l;
            }

            m_FSM.Driver.LockUIRespond.Invoke(l);
        }

        #region TableView

        public TableViewCell GetCellByIdx(int idx)
        {
            switch (DataManager.ins.functionType)
            {
                case FunctionType.ProductionDateOfOffShelf:
                    {
                        OffShelfProductionDateItemUI ui = null;
                        if (PoolsManager.ins.HaveGameObject(offShelfProductionDateItemPrefab.name))
                        {
                            ui = PoolsManager.ins.Get(offShelfProductionDateItemPrefab.name).GetComponent<OffShelfProductionDateItemUI>();
                        }
                        else
                        {
                            ui = GameObject.Instantiate(offShelfProductionDateItemPrefab).GetComponent<OffShelfProductionDateItemUI>();
                            ui.name = offShelfProductionDateItemPrefab.name;
                        }
                        ui.Refresh(OffShelfProductionDateQueryDatabase.ins.Get(idx));
                        ui.SetLockUIRespond(DataManager.ins.lockProductionDatePanel);

                        return ui;
                    }
                case FunctionType.OffShelfDate:
                    {
                        OffShelfDateItemUI ui = null;
                        if (PoolsManager.ins.HaveGameObject(offShelfDateItemPrefab.name))
                        {
                            ui = PoolsManager.ins.Get(offShelfDateItemPrefab.name).GetComponent<OffShelfDateItemUI>();
                        }
                        else
                        {
                            ui = GameObject.Instantiate(offShelfDateItemPrefab).GetComponent<OffShelfDateItemUI>();
                            ui.name = offShelfDateItemPrefab.name;
                        }
                        ui.Refresh(OffShelfDateQueryDatabase.ins.Get(idx));
                        ui.SetLockUIRespond(DataManager.ins.lockOffShelfDatePanel);

                        return ui;
                    }
                default:
                    {
                        Debug.LogError("未知类型");
                        return null;
                    }
            }
        }

        public Vector2 GetCellSizeByIdx(int idx)
        {
            switch (DataManager.ins.functionType)
            {
                case FunctionType.ProductionDateOfOffShelf:
                    {
                        return new Vector2(720f, 145f);
                    }
                case FunctionType.OffShelfDate:
                    {
                        return new Vector2(720f, 145f);
                    }
                default:
                    {
                        Debug.LogError("未知类型");
                        return Vector2.zero;
                    }
            }
        }

        public int GetCellSum()
        {
            switch (DataManager.ins.functionType)
            {
                case FunctionType.ProductionDateOfOffShelf:
                    {
                        return OffShelfProductionDateQueryDatabase.ins.Count();
                    }
                case FunctionType.OffShelfDate:
                    {
                        return OffShelfDateQueryDatabase.ins.Count();
                    }
                default:
                    {
                        Debug.LogError("未知类型");
                        return 0;
                    }
            }
        }

        public void PutCell(TableViewCell cell)
        {
            PoolsManager.ins.Put(cell.name, cell.gameObject);
        }

        #endregion

        private void OnFunctionTypeChanged()
        {
            m_FSM.ChangeState(DataManager.ins.functionType);
        }

        private void OnCloseTipPopup(TipPopupPanel.ReplyKind kind)
        {
            Messenger.RemoveListener<TipPopupPanel.ReplyKind>(EventName.CloseTipPopup, OnCloseTipPopup);

            m_FSM.Driver.CloseTipPopup.Invoke(kind);
        }

        private void Reload() { m_TableView.Reload(); }

        #region FSM

        #region 下架生产日期

        private void ProductionDateOfOffShelf_Enter()
        {
            foreach (var btn in transform.Find("Bar").FindComponentsInChildren<Button>(false))
            {
                btn.interactable = !DataManager.ins.lockProductionDatePanel;
            }

            m_LockUIRespondToggle.isOn = DataManager.ins.lockProductionDatePanel;

            Reload();

            Messenger.AddListener(EventName.ReloadOffShelfProductionDatePanel, Reload);
        }

        private void ProductionDateOfOffShelf_Exit()
        {
            Messenger.RemoveListener(EventName.ReloadOffShelfProductionDatePanel, Reload);
        }

        private void ProductionDateOfOffShelf_Destroy()
        {
            ProductionDateOfOffShelf_Exit();
        }

        private void ProductionDateOfOffShelf_NewBtn()
        {
            var data = new OffShelfProductionDateQuery();
            OffShelfProductionDateQueryDatabase.ins.Add(data);
            Reload();
        }

        private void ProductionDateOfOffShelf_CloseTipPopup(TipPopupPanel.ReplyKind kind)
        {
            if (kind == TipPopupPanel.ReplyKind.Yes)
            {
                OffShelfProductionDateQueryDatabase.ins.Clear();
                Reload();
            }
        }

        private void ProductionDateOfOffShelf_LockUIRespond(bool b)
        {
            DataManager.ins.lockProductionDatePanel = b;
            Messenger.Broadcast<bool>(EventName.LockOffShelfProductionDateItem, b);
        }

        #endregion

        #region 下架日期

        private void OffShelfDate_Enter()
        {
            foreach (var btn in transform.Find("Bar").FindComponentsInChildren<Button>(false))
            {
                btn.interactable = !DataManager.ins.lockOffShelfDatePanel;
            }

            m_LockUIRespondToggle.isOn = DataManager.ins.lockOffShelfDatePanel;

            Reload();

            Messenger.AddListener(EventName.ReloadOffShelfDatePanel, Reload);
        }

        private void OffShelfDate_Exit()
        {
            Messenger.RemoveListener(EventName.ReloadOffShelfDatePanel, Reload);
        }

        private void OffShelfDate_Destroy()
        {
            OffShelfDate_Exit();
        }

        private void OffShelfDate_NewBtn()
        {
            var data = new OffShelfDateQuery();
            OffShelfDateQueryDatabase.ins.Add(data);
            Reload();
        }

        private void OffShelfDate_CloseTipPopup(TipPopupPanel.ReplyKind kind)
        {
            if (kind == TipPopupPanel.ReplyKind.Yes)
            {
                OffShelfDateQueryDatabase.ins.Clear();
                Reload();
            }
        }

        private void OffShelfDate_LockUIRespond(bool b)
        {
            DataManager.ins.lockOffShelfDatePanel = b;
            Messenger.Broadcast<bool>(EventName.LockOffShelfDateItem, b);
        }

        #endregion

        private class Driver
        {
            public StateEvent Destroy;

            public StateEvent NewBtn;

            public StateEvent<TipPopupPanel.ReplyKind> CloseTipPopup;

            public StateEvent<bool> LockUIRespond;
        }

        #endregion

    }
}